<template>
  <div>
    <div
      class="easy-container-min flex align-items-center"
      :class="[
        { 'el-alert--success is-light': selectedFolder.id === folder.id },
        curMoving ? 'bg-fafafa not-allowed' : 'pointer',
      ]"
      @click="selectFolder"
    >
      <i class="cell f-normal shrink-0" :class="folderIcon"></i>
      <div class="flex" style="min-width: 0;">
        <span class="line1">{{ folder.title }}</span>
        <span class="shrink-0 p-x-16">{{ curMoving ? '(当前移动的目录)' : '' }}</span>
      </div>
    </div>
    <div
      v-show="folderOpened && !curMoving"
      class="p-l-16 custom-table"
      v-infinite-scroll="infiniteLoad"
      :infinite-scroll-disabled="!loadPage || loading"
    >
      <folders-tree-item
        v-for="item in children"
        :key="item.id"
        :folder="item"
        :moving-id="movingId"
      />
    </div>
  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex';
import { formatResources } from '@/components/spaces/resources-v2/format';

export default {
  name: 'folders-tree-item',
  props: {
    folder: Object,
    movingId: Number,
  },
  data() {
    return {
      children: [],
      loading: false,
      loaded: false,
      folderOpened: false,
      loadPage: 1,
    };
  },
  computed: {
    ...mapState(['selectedFolder']),
    // 当前正在移动这个目录
    curMoving() { return this.movingId === this.folder.id; },
    folderIcon() {
      if (this.loading) return 'el-icon-loading';
      else if (this.folderOpened && !this.curMoving) return 'el-icon-folder-opened';
      return 'el-icon-folder';
    },
  },
  methods: {
    ...mapActions(['setSelectedFolder']),
    // 选择了目录
    selectFolder() {
      if (this.movingId === this.folder.id) { // 当移动时选择了自己时
        return;
      }
      this.setSelectedFolder(this.folder);
      if (this.loaded) {
        this.folderOpened = !this.folderOpened;
        return;
      }
      this.loadFolders();
    },
    loadFolders() {
      this.loading = true;
      this.$api.spaceResources.index({
        spaceId: this.folder.space.id,
        type: ['ProductFolder'],
        folderId: this.folder.id,
        page: this.loadPage,
      }).then((res) => {
        this.children = this.children.concat(formatResources(res.data));
        this.loaded = true;
        this.folderOpened = true;
        this.loadPage = res.kaminari.next_page;
      }).catch(() => {})
        .then(() => { this.loading = false; });
    },
    infiniteLoad() {
      if (this.loadPage > 1) this.loadFolders();
    },
  },
};
</script>

<style></style>
